<template>
  <div :class="{'has-logo': showLogo}">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
        router
      >
        <sidebar-item 
          v-for="route in permission_routes" 
          :key="route.path" 
          :item="route" 
          :base-path="route.path"
        />
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import Logo from './Logo.vue'
import SidebarItem from './SidebarItem.vue'
import { routes } from '@/router' // 导入路由配置

// 菜单样式变量
const variables = {
  menuBg: '#304156',
  menuText: '#bfcbd9',
  menuActiveText: '#409eff'
}

const route = useRoute()
const appStore = useAppStore()
const userStore = useUserStore()

// 检查用户是否有权限访问路由
const hasPermission = (route) => {
  if (!route.meta || !route.meta.roles) {
    return true // 没有角色限制的路由，所有人都可以访问
  }

  const userRoles = userStore.roles || []
  return route.meta.roles.some(role => userRoles.includes(role))
}

// 从路由配置中过滤出要显示在菜单中的路由
const permission_routes = computed(() => {
  return routes.filter(route => {
    // 跳过登录页和不需要显示的路由
    if (route.path === '/login' || (route.meta && route.meta.hidden)) {
      return false
    }

    // 检查权限
    if (!hasPermission(route)) {
      return false
    }

    // 处理子路由，过滤掉隐藏的子路由和无权限的子路由
    if (route.children) {
      route.children = route.children.filter(child => {
        if (child.meta && child.meta.hidden) {
          return false
        }
        return hasPermission(child)
      })
    }

    return true
  })
})

const showLogo = computed(() => true)
const isCollapse = computed(() => !appStore.sidebar.opened)
const activeMenu = computed(() => {
  const { meta, path } = route
  if (meta.activeMenu) {
    return meta.activeMenu
  }
  return path
})
</script>

<style lang="scss" scoped>
.has-logo {
  .el-scrollbar {
    height: calc(100% - 50px);
  }
}

.el-scrollbar {
  height: 100%;
}

.scrollbar-wrapper {
  overflow-x: hidden !important;
}

.el-menu {
  border: none;
  height: 100%;
  width: 100% !important;
}
</style>
